<template>
  <div class="box">
    <div id="container" style="width:100%; height:100%"></div>
  </div>
</template>

<script>
import AMap from 'AMap' // 引入高德地图
export default {
  props: ["clientId"],
  data: function () {
    return {
      map: '',
      marker: '',
      lng: "",
      lat: ""
    }
  },
  mounted() {
    this.init(this.lng, this.lat)
  },
  methods: {

    init(lng, lat) {
      this.map = new AMap.Map('container', {
        animateEnable:true,
        resizeEnable: true,
        mapStyle: "amap://styles/dark", // 设置颜色底层
        //center: [lng, lat],
        expandZoomRange: true,
        buildingAnimation: true,
        zoom: 18,

        
        zooms: [3, 20],
        enableHighAccuracy: true,
        viewMode: '3D'//使用3D视图

      });
    },
    initmarker(lng, lat,angle) {
      var icon = new AMap.Icon({
        size: new AMap.Size(52, 26), // 图标尺寸
        image: "https://webapi.amap.com/images/car.png",
      
       // imageSize: new AMap.Size(52, 26) // 根据所设置的大小拉伸或压缩图片
      });
      this.marker = new AMap.Marker({
        zoom: 17,
        icon: icon,
        position: [lng, lat],//位置
        angle:angle-90
      })
      this.map.setCenter([lng,lat]);
      this.map.add(this.marker);//添加到地图
    },


    initWebSocket() { //初始化weosocket
      const wsuri = IPConfig.BASE_WSURL+'/websocket/' + localStorage.getItem("token");
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen() {
      // "80006005177"
      this.websocketsend(this.clientId);
    },
    websocketonerror() {//连接建立失败重连
      this.initWebSocket();
    },
    websocketonmessage(e) {
      if (e.data.includes("后端")) {
        console.log(e.data)
      } else if(e.data.includes("非")){
        console.log(e.data)
      }else {
        this.map.remove(this.marker)
        //数据接收
        const redata = JSON.parse(e.data);
        this.initmarker(redata.longitude , redata.latitude,redata.direction )
      }
    },
    websocketsend(Data) {//数据发送
      this.websock.send(Data);
    },
    websocketclose(e) {  //关闭
      
    },

  },
  watch:{
    clientId(){
      this.websock.close() 
      this.init(this.lng, this.lat)
      this.initWebSocket();
    }
  },
  created() {
    this.initWebSocket();
  },
  destroyed() {
    this.websock.close() //离开路由之后断开websocket连接
  },
}

</script>
<style scoped>

:deep(.amap-logo ){
  z-index:-1;
}

</style>
